package gate

import (
	"message"

	"github.com/golang/protobuf/proto"
)

var processor = NewProcessor()

type Processor struct {
	msgHandler MsgHandler
}

type MsgHandler func(interface{}, interface{})

func NewProcessor() *Processor {
	p := new(Processor)
	return p
}

func (p *Processor) SetHandler(msgHandler MsgHandler) {
	p.msgHandler = msgHandler
}

// goroutine safe
func (p *Processor) Route(msg interface{}, userData interface{}) error {
	p.msgHandler(msg, userData)
	return nil
}

// 序列化给客户端的RPCResponse包
func (p *Processor) Marshal(msg interface{}) ([][]byte, error) {
	//log.Debug("gate.protobuf--Marshal:  %v", msg)
	data, err := proto.Marshal(msg.(proto.Message))
	return [][]byte{data}, err
}

// 反序列化客户端的RPCRequest包
func (p *Processor) Unmarshal(data []byte) (interface{}, error) {
	msg := &message.RPCRequest{}
	return msg, proto.Unmarshal(data, msg)
}
